package red.dao.impl;


import net.sf.json.JSONArray;
import red.dao.UserDao;
import red.model.UserModel;
import red.util.MysqlConnectUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserDaoImpl implements UserDao {

    private MysqlConnectUtils mysqlConnectUtils = new MysqlConnectUtils();
    private PreparedStatement preparedStatement;
    private ResultSet rs;

    @Override
    public UserModel getUser(Integer uid) {
        return null;
    }

    @Override
    public List<UserModel> getUser() {
        return null;
    }

    @Override
    public UserModel savaUser(UserModel userModel) {
        String user_id = userModel.getUser_id();
        String user_name = userModel.getUser_name();
        String password = userModel.getPassword();
        MysqlConnectUtils conn = new MysqlConnectUtils();
        List list = new ArrayList();
        String sql2 = "select * from user where user_name='" + user_name + "'";
        try {
            conn.connection();
            preparedStatement = conn.conn.prepareStatement(sql2);
            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                UserModel recommendBean = new UserModel();
                recommendBean.setUser_name(rs.getString("user_name"));
                list.add(recommendBean);
            }
            JSONArray jsonObject = JSONArray.fromObject(list);
            if (jsonObject.size() == 0) {
                String sql = "insert into user(user_id,user_name,password,logintime) "
                        + "value('" + user_id + "','" + user_name + "','" + password + "',now())";
                mysqlConnectUtils.insert(sql);
                return userModel;
            }else {
                return userModel;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userModel;
    }

    @Override
    public List<UserModel> loginUser(UserModel userModel) {
        String user_name = userModel.getUser_name();
        String password = userModel.getPassword();
        String sql = "select * from user where "+"user_name = '"+user_name+"' and password = '"+password+"'";
        List<UserModel> ums =new ArrayList<>();
        List<Map<String, Object>> list = mysqlConnectUtils.list(sql);
        for(int i=0;i<list.size();i++){
            Map<String ,Object> row=list.get(i);
            UserModel usermodel=new UserModel();
            usermodel.setUser_name(row.get("user_name").toString());
            usermodel.setPassword(row.get("password").toString());
            ums.add(usermodel);
        }
        return ums;
    }

    @Override
    public UserModel findUser(UserModel userModel) {
        return null;
    }




    @Override
    public UserModel updateUser(UserModel userModel) {
        return null;
    }
}
